package leetCode.offer66;

import java.util.Arrays;

public class Solution5 implements Solution{


    /**
     * 空间复杂度O(1)解法
     * @param a
     * @return
     */
    @Override
    public int[] constructArr(int[] a) {
        if(a==null||a.length==0) return new int[0];
        if(a.length==1) return a;
        int after = 1;
        int pre = 1;
        int[] result = new int[a.length];
        System.arraycopy(a,0,result,0,a.length);
        int length = a.length-1;
        for (int i=0;i<a.length;i++) {
            after *= result[length];
            result[length] = after;
            pre *= a[i];
            a[i] = pre;
            length--;
        }
        for(int i=0;i<a.length;i++) {
            if(i==0){
                result[i] = result[1];
            }
            else if(i==a.length-1){
                result[i] = a[a.length-2];
            }
            else{
                result[i] = result[i+1]*a[i-1];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution5().constructArr(new int[]{4,3,2,1,2})));
    }
}
